package com.jvm123.blog.controller

import com.jvm123.blog.dao.CollectRepos
import com.jvm123.blog.dao.PostRepos
import com.jvm123.blog.entity.Collect
import com.jvm123.blog.entity.Post
import com.jvm123.blog.entity.Term
import com.jvm123.blog.service.TermService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

import javax.servlet.http.HttpServletRequest

/**
 *
 * @author yawn http://jvm123.com
 *     2019/10/25 11:07
 */
@RestController
@RequestMapping("site")
class SiteController {

    @Autowired
    CollectRepos collectRepos
    @Autowired
    PostRepos postRepos
    @Autowired
    TermService termService

    @GetMapping(value = "map", produces = MediaType.APPLICATION_JSON_VALUE)
    String siteMap(HttpServletRequest request) {
        String baseUrl = baseUrl(request)
        StringBuffer sb = new StringBuffer()
        sb.append(baseUrl).append("index").append(".html").append("\n")
        sb.append(baseUrl).append("blogs").append(".html").append("\n")
        sb.append(baseUrl).append("series").append(".html").append("\n")
        sb.append(baseUrl).append("videos").append(".html").append("\n")
        sb.append(baseUrl).append("tools").append(".html").append("\n")
        sb.append(baseUrl).append("tags").append(".html").append("\n")
        Iterable<Collect> allCollects = collectRepos.findAll()
        for (Collect collect : allCollects) {
            sb.append(baseUrl).append("collect/").append(collect.id).append(".html").append("\n")
        }
        for (Collect collect : allCollects) {
            sb.append(baseUrl).append("collect/").append(collect.id).append("/").append(collect.title).append(".html").append("\n")
        }
        Iterable<Post> allPosts = postRepos.findAll()
        for (Post post : allPosts) {
            sb.append(baseUrl).append("post/").append(post.id).append("/").append(post.postName).append(".html").append("\n")
        }
        for (Post post : allPosts) {
            sb.append(baseUrl).append("post/").append(post.id).append(".html").append("\n")
        }
        List<Term> cateTerms = termService.findCategories()
        List<Term> tagTerms = termService.findTags()
        new String(sb)
    }

    @GetMapping(value = "xml/map", produces = MediaType.APPLICATION_XML_VALUE)
    Map dynamicSiteMap(HttpServletRequest request) {
        String baseUrl = baseUrl(request)
        String uri = request.getRequestURI()

        new HashMap() {{
            put("ddd", baseUrl + uri)
        }}
    }

    private String baseUrl(HttpServletRequest request) {
        request.getScheme()
        request.getServerPort()
        "https://" + request.getServerName() + "/"
    }
}
